import navbarTemplate from "./Navbar.html";
import { NotificationItem } from "./Notification/NotificationItem";
import logoLight1 from "../../assets/images/logo-light.png";
import logoLight2 from "../../assets/images/logo-sm.png";
import { DomUtils } from "../../utils/DomUtils";
import { getCurrentUser } from "../../services/userService";
import { notificationService } from "../../services/notificationService";

export class Navbar {
  constructor(data = {}) {
    this.data = {
      user: { username: "", avatar: "" },
      notifications: [],
      unreadCount: 0,
      ...data,
    };

    // ✅ 监听头像更新事件
    window.addEventListener("user-info-updated", async () => {
      console.log("🔁 收到头像更新事件，重新加载用户数据");
      await this.loadData(); // 重新获取头像
      const newDom = this.render(); // 重新渲染 Navbar HTML
      const oldDom = document.querySelector("#navbar-container"); // 假设你有固定的挂载点
      if (oldDom && newDom) {
        oldDom.replaceWith(newDom); // 替换
      }
    });
  }

  async loadData() {
    try {
      const user = await getCurrentUser(); // 保证即使 notifications 报错也能加载用户
      this.data.user = {
        username: user.username,
        avatar: user.avatar?.startsWith("data:")
          ? user.avatar
          : `data:image/jpeg;base64,${user.avatar}`,
      };
    } catch (err) {
      console.error("获取用户失败：", err);
    }

    try {
      const notifications = await notificationService.getNotifications();
      this.data.notifications = notifications.items || [];
      this.data.unreadCount = notifications.unreadCount || 0;
    } catch (err) {
      console.warn("获取通知失败，使用空列表：", err);
      this.data.notifications = [];
      this.data.unreadCount = 0;
    }

    console.log("Navbar 渲染数据：", this.data);
    return this;
  }

  render() {
    const notificationsHtml = this.data.notifications
      .map((item) => new NotificationItem(item).render())
      .join("");

    const template = navbarTemplate
      .replace(/{{user\.username}}/g, this.data.user.username)
      .replace(/{{user\.avatar}}/g, this.data.user.avatar)
      .replace(/{{unreadCount}}/g, this.data.unreadCount)
      .replace("{{notifications}}", notificationsHtml)
      .replace(/{{logoPath1}}/g, logoLight1)
      .replace("{{logoPath2}}", logoLight2);

    //  更安全的渲染方式（整个 body）
    const parser = new DOMParser();
    const doc = parser.parseFromString(template, "text/html");

    // 获取最外层元素（整个 Navbar）
    return doc.body.firstElementChild;

    return DomUtils.convertToDom(template);
  }
}
